/*
 * Copyright 2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package log4flex.target
{
	import log4flex.Log4FlexConstants;
	import log4flex.core.RemoteLogRecord;
	
	import mx.logging.ILogger;
	import mx.logging.LogEvent;
	import mx.logging.targets.LineFormattedTarget;
	import mx.rpc.remoting.RemoteObject;

	/**
	 * 
	 * Logging target to log to a server using flash remoting(RemoteObject/AMF)
	 * 
	 */ 
	public class RemotingTarget extends LineFormattedTarget
	{
		use namespace mx_internal;
		public function RemotingTarget()
		{
			
			super();
			_destinationService=Log4FlexConstants.DEFAULT_REMOTE_TARGET;
			
			remoteObject=new RemoteObject();
			remoteObject.destination=_destinationService;
		}
		
		private var remoteObject:RemoteObject;
		
		private var _destinationService:String;
		
		/**
		 * 
		 * @param  Remoting Destination name. Default - Log4FlexService
		 * 
		 */				
		public  function  set destinationService(name:String):void {
			_destinationService=name;		
		}
		
		/**
		 * 
		 * @return Remoting Service name 
		 * 
		 */		
		public function get destinationService():String {
			return _destinationService;
		}
		
		/**
		 * 
		 * Log the event to remote target. 
		 * Log Filtering is done in client side to involve large data transfers.
		 * 
		 * TODO - Implement a heavyweight version which logs the entire data.
		 * 
		 * @param event
		 * 
		 */		
		public override function logEvent(event:LogEvent):void {
			var remoteEvt:RemoteLogRecord=Log4FlexUtils.newRemoteLogRecord(event);
			
			remoteEvt.includeCategory=this.includeCategory;
			remoteEvt.category=this.includeCategory?(event.target as ILogger).category;
			
			
			remoteEvt.includeLevel=this.includeLevel;
			remoteEvt.level=this.includeLevel?event.level;

			
			remoteEvt.includeTime=this.includeTime;
			remoteEvt.includeDate=this.includeDate;
			remoteEvt.date=this.includeDate?new Date();
			
			
			//TODO - Remote Logging
			
			//FIXME - Logging to trace console initially.
			if(consoleLog) {
				super.logEvent(event);
			}
		}
		
        // override this method to perform the redirection to the desired output
		 override mx_internal function internalLog(message:String):void
	    {
				trace(message);
	    }
		
		public var consoleLog:Boolean;
	}
}